const express = require('express')
const browser = require('./utils/browser')
const path = require('path')

const port = process.env.LEANCLOUD_APP_PORT || 3300
const app = express()

// 设置视图解析器
app.set('view engine', 'ejs')
app.set('views', path.resolve(__dirname, 'views'))

const ResponseTime = require('response-time')
app.use(ResponseTime())

app.use(express.static(path.resolve(__dirname, 'public')))

// app.use((req, res, next) => {
//     console.log('before', res.getHeaders(), res.getHeader('x-response-time'))
//     res.locals.responseTime = res.getHeader('x-response-time')
//     next()
//     res.locals.responseTime = res.getHeader('x-response-time')
//     console.log('next', res.getHeaders(), res.getHeader('x-response-time'))
// })

const CookieParser = require('cookie-parser')
app.use(CookieParser())


// 计算页面耗时中间件
app.use((req, res, next) => {
    const startAt = process.hrtime()

    // 重写 render 方法
    const render = res.render
    res.render = function () {
        var diff = process.hrtime(startAt)
        var time = diff[0] * 1e3 + diff[1] * 1e-6
        res.locals.responseTime = time.toFixed(3) + '毫秒'
        render.apply(this, arguments)
    }

    next()
})

app.get('/', async (req, res) => {
    await new Promise(resovle => {
        setTimeout(resovle, Math.random() * 1000)
    })
    res.render('index', {
        title: 'hi~',
        list: [
            'a',
            'b',
            'c'
        ]
    })
})

app.get('/capture', async (req, res) => {
    console.dir(req.cookies)
    const pic = await browser.capture('智慧园区')
    // res.send('ok')

    console.log(pic)

    res.set({
        'Content-Type': 'image/png'
    }).end(pic)
})

process.on('beforeExit', async () => {
    console.log('process exit..')
    await browser.close()
})

app.listen(port, () => {
    console.log(`server started at http://localhost:${port}`)
})
